<template>
  <div>
    <el-tree
      ref="refTree"
      node-key="id"
      show-checkbox
      default-expand-all
      check-strictly
      :data="list"
      :props="{label: 'name'}"
    />

    <el-button @click="hClose">取 消</el-button>
    <el-button type="primary" @click="hSubmit">确 定</el-button>
  </div>
</template>

<script>
import { tranListToTreeData } from '@/utils/index.js'
import { getPermissionList } from '@/api/permisson'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    // 1. 所有的权限
    this.loadPermissions()

    // 2. 当前的角色的权限
    this.loadPermissionsById()
  },

  methods: {
    hClose() {
      this.$emit('close')
    },
    async hSubmit() {
      // 1. 获取当前用户的选择 ----> 调用api
      try {
        const permIds = this.$refs.refTree.getCheckedKeys()
        await assignPerm({ id: this.curId, permIds })
        console.log(permIds)
        this.$message.success('操作成功')
        this.$emit('close')
      } catch (err) {
        console.log()
      }
    },
    async loadPermissionsById() {
      try {
        const res = await getRoleDetail(this.curId)
        console.log('res', res)

        // 设置当前选中的节点
        this.$refs.refTree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log('错误', err)
      }
    },
    async loadPermissions() {
      try {
        const res = await getPermissionList()
        console.log('权限点', res)
        // 保存数据
        // 数组数据转成tree
        this.list = tranListToTreeData(res.data)
      } catch (err) {
        console.log('错误', err)
      }
    }
  }
}
</script>
